package com.yijiaganxi.member.api.takeAddress;

import java.util.List;

import javax.validation.constraints.NotBlank;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yijiaganxi.common.entity.takeAddress.YjgxTakeAddress;
import org.yijiaganxi.common.res.R;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.yijiaganxi.common.GlobalConstants;
import com.yijiaganxi.member.service.takeAddress.YjgxTakeAddressService;


@RestController
@RequestMapping("/member/yjgxTakeAddress/"+GlobalConstants.WECHAT_FLAG)
@Validated
public class TakeAddressApi {

	@Autowired
	public YjgxTakeAddressService  takeAddressService;
	
	/**
	 * 根据opnid查询用户地址列表
	 * @param openId
	 * @return
	 */
	@GetMapping("getTakeAddressListByOpneId")
	public R getTakeAddressListByOpneId(@NotBlank(message = "openId不能为空") String openId) {
		return R.opertionListResponse(takeAddressService.selectList(new EntityWrapper<YjgxTakeAddress>()
				.eq("openId", openId)));
	}
	
	/**
	 * 根据openId查询用户默认收货地址
	 * @param openId
	 * @return
	 */
	@GetMapping("getDefaulTakeAddressByOpenId")
	public R getDefaulTakeAddressByOpenId(@NotBlank(message = "openId不能为空") String openId) {
		return R.opertionListResponse(takeAddressService.selectList(new EntityWrapper<YjgxTakeAddress>()
				.eq("opeId", openId)
				.and()
				.eq("isDetault", "1")));
	}
	
	/**
	 * 设置用户默认收货地址
	 * @param takeAddressId
	 * @return
	 */
	@PostMapping("settingDefaultTakeAddress")
	public R settingDefaultTakeAddress(@NotBlank(message = "takeAddressId不能为空") String takeAddressId) {
		YjgxTakeAddress settingTakeAddress = takeAddressService.selectById(takeAddressId);
		if(settingTakeAddress==null)
			return R.ok("地址不存在");
		
		Long openId = settingTakeAddress.getOpenId();
		
		List<YjgxTakeAddress> selectList = takeAddressService.selectList(new EntityWrapper<YjgxTakeAddress>()
				.eq("openId", openId));
		
		for(YjgxTakeAddress takeAddressItem: selectList) {
			if(takeAddressItem.equals(takeAddressId)) {
				takeAddressItem.setIsDetault(1);
			}else
				takeAddressItem.setIsDetault(0);
		}
		
		return R.insertOrUpdateResponse(takeAddressService.updateBatchById(selectList));
	}
	
	/**
	 * 添加收货地址
	 * @param takeAddress
	 * @return
	 */
	@PostMapping("addTakeAddresss")
	public R addTakeAddresss(@Validated YjgxTakeAddress takeAddress) {
		return R.insertOrUpdateResponse(takeAddressService.insert(takeAddress));
	}
}
